<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\AgricGoodsCategory;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Controllers\AdminController;

class AgricGoodsCategoryController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new AgricGoodsCategory(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('category_name');
            $grid->column('category_sort');
            $grid->column('status')->display(function ($status) {
                return $status ? '可用' : '不可用';
            });
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();

            $grid->quickSearch(['category_name'])->placeholder('搜索...');
//            $grid->filter(function (Grid\Filter $filter) {
//                $filter->equal('category_name');
//
//            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new AgricGoodsCategory(), function (Show $show) {
            $show->field('id');
            $show->field('category_name');
            $show->field('category_sort');
            $show->field('status')->as(function ($status) {
                return $status ? '可用' : '不可用';
            });
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new AgricGoodsCategory(), function (Form $form) {
            $form->display('id');
            $form->text('category_name');
            $form->number('category_sort');
            $form->radio('status', '状态')->options([1 => '可用', 0 => '不可用'])->default(1);
        
            $form->display('created_at');
            $form->display('updated_at');

            $form->submitted(function ($form) {
                // 分类名验证
                $query = \App\Models\AgricGoodsCategory::query();
                $query->where('category_name', $form->category_name);
                if ($form->model()->id) {
                    $query->where('id', '!=', $form->model()->id);
                }
                $checkCategory = $query->first();
                if ($checkCategory) {
                    $form->responseValidationMessages('category_name', '分类名称已存在');
                }
            });
        });
    }
}
